package load.ogp;

import core.OutPort;
import load.parent.Wrapper;
import core.Port;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import load.parent.Function;
import view.GUI.LabelReader;

/**
 *
 * @author Ben
 */
public class Class extends Wrapper{
    private Map<Port, String> portToFieldName = new HashMap<Port, String>();

    public Class(java.lang.Class c){
        super(c,true);
        addOtherFields();
    }

    public Class() {
        super(true);
        addOtherFields();
    }

    private void addOtherFields(){
        try{
            addConstructorNodes();
            addStaticFields();
        }catch(Exception ex){
           JOptionPane.showMessageDialog(null,"Type: "+ ex.getMessage(),
              LabelReader.getInstance().getString("Error"), JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addStaticFields() throws Exception{
        for(final Field f : getWrappedClass().getFields()){
             if(Modifier.isStatic(f.getModifiers())){
                OutPort p = new OutPort(classMapper(f.getType())){
                    public Object getValueInternal() {
                        try{
                            String name = portToFieldName.get(this);
                            Field field = getWrappedClass().getField(name);
                            return field.get(null);
                        }catch(Exception e){
                            return null;
                        }
                    }
                };
                this.putPort(f.getName(), p);
                portToFieldName.put(p, f.getName());
             }
        }
    }

    private void addConstructorNodes() throws Exception{
        for(java.lang.reflect.Constructor ctr : getWrappedClass().getConstructors()){
            Port p = null;
            if(ctr.getParameterTypes().length ==0){
                p = addOutPort(ctr);
            }else{
                p = addFunctionNode(new Function(ctr,this));
            }
            super.putPort(uniqueNameFrom(ctr.getName()), p);
        }
    }
}
